package com.jiyun.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jiyun.dao.*;
import com.jiyun.entity.PageResult;
import com.jiyun.pojo.goods.*;
import com.jiyun.service.goods.SpuService;
import com.jiyun.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    /**
     * 返回全部记录
     * @return
     */
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Spu> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectAll();
        return new PageResult<Spu>(spus.getTotal(),spus.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectByExample(example);
        return new PageResult<Spu>(spus.getTotal(),spus.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param spu
     */
    public void add(Spu spu) {
        spuMapper.insert(spu);
    }

    /**
     * 修改
     * @param spu
     */
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        spuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveGoods(Goods goods) {
        // 获取从前台传递过来的spu对象
        Spu spu = goods.getSpu();
        spu.setId(idWorker.nextId()+"");
        spuMapper.insert(spu);

        Date date = new Date();
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

        // 获取前台传递过来的sku对象
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            // 把sku中的信息，进行特殊处理
            sku.setId(idWorker.nextId()+"");
            sku.setSpuId(spu.getId());
            // 组装 sku的名字
            String name = spu.getName();

            Map map = JSON.parseObject(sku.getSpec(), Map.class);
            for (Object value : map.values()) {
                name += value.toString();
            }
            sku.setName(name);
            sku.setCreateTime(date);//创建日期
            sku.setUpdateTime(date);//修改日期
            sku.setCategoryId(spu.getCategory3Id());//分类id
            sku.setCategoryName(category.getName());//分类名称
            sku.setCommentNum(0);//评论数
            sku.setSaleNum(0);//销售数量

            skuMapper.insert(sku);
        }

        // 得到当前商品的品牌和分类的id
        Integer brandId = spu.getBrandId();
        Integer category3Id = spu.getCategory3Id();

        Example example = new Example(CategoryBrand.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("brandId",brandId);
        criteria.andEqualTo("categoryId",category3Id);
        int count = categoryBrandMapper.selectCountByExample(example);
        if(count == 0){
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setBrandId(brandId);
            categoryBrand.setCategoryId(category3Id);
            categoryBrandMapper.insert(categoryBrand);
        }

    }

    @Autowired
    ParaMapper paraMapper;
    @Autowired
    SpecMapper specMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    TemplateMapper templateMapper;
    @Autowired
    AlbumMapper albumMapper;

    @Override
    public Map initAllData() {
        // 查询所有分类信息
        List<Category> categoryList = categoryMapper.selectAll();
        List<Para> paraList = paraMapper.selectAll();
        List<Spec> specList = specMapper.selectAll();
        List<Brand> brandList = brandMapper.selectAll();
        List<Template> templateList = templateMapper.selectAll();
        List<Album> albumList = albumMapper.selectAll();

        Map map = new HashMap();
        map.put("categoryList",categoryList);
        map.put("paraList",paraList);
        map.put("specList",specList);
        map.put("brandList",brandList);
        map.put("templateList",templateList);
        map.put("albumList",albumList);

        return map;
    }

    @Override
    public Goods findGoodsById(Long id) {
        // spu   skuList
        Spu spu = spuMapper.selectByPrimaryKey(id);

        // 根据spuid查询关联sku的集合
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<Sku> skuList = skuMapper.selectByExample(example);

        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);
        return goods;
    }

    @Override
    public void updateGoods(Goods goods) {
        Spu spu = goods.getSpu();
        spuMapper.updateByPrimaryKey(spu);

        // spu一些关联的sku
        // 可能删除sku，也可能添加sku
        // 快刀斩乱麻  先删除所有关联的sku，再重新添加就行了
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spu.getId());
        skuMapper.deleteByExample(example);

        Date date = new Date();
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

        // 获取前台传递过来的sku对象
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            // 把sku中的信息，进行特殊处理
            sku.setId(idWorker.nextId()+"");
            sku.setSpuId(spu.getId());
            // 组装 sku的名字
            String name = spu.getName();

            Map map = JSON.parseObject(sku.getSpec(), Map.class);
            for (Object value : map.values()) {
                name += value.toString();
            }
            sku.setName(name);
            sku.setCreateTime(date);//创建日期
            sku.setUpdateTime(date);//修改日期
            sku.setCategoryId(spu.getCategory3Id());//分类id
            sku.setCategoryName(category.getName());//分类名称
            sku.setCommentNum(0);//评论数
            sku.setSaleNum(0);//销售数量

            if(sku.getSpec()==null || "".equals(sku.getSpec())){
                sku.setSpec("{}");
            }

            skuMapper.insert(sku);
        }

        // 得到当前商品的品牌和分类的id
        Integer brandId = spu.getBrandId();
        Integer category3Id = spu.getCategory3Id();

        Example example1 = new Example(CategoryBrand.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("brandId",brandId);
        criteria1.andEqualTo("categoryId",category3Id);
        int count = categoryBrandMapper.selectCountByExample(example1);
        if(count == 0){
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setBrandId(brandId);
            categoryBrand.setCategoryId(category3Id);
            categoryBrandMapper.insert(categoryBrand);
        }

    }

    @Override
    public void audit(Long id,String status) {
        Spu spu = new Spu();
        spu.setId(id+"");
        // 审核完成
        spu.setStatus(status);
        spu.setIsMarketable(status);

        // 只修改不为null的字段  updateByPrimaryKeySelective
        spuMapper.updateByPrimaryKeySelective(spu);

    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andLike("sn","%"+searchMap.get("sn")+"%");
            }
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
            }
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
            }
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
            }
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
            }
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
            }
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
            }
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
            }
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andLike("isMarketable","%"+searchMap.get("isMarketable")+"%");
            }
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andLike("isEnableSpec","%"+searchMap.get("isEnableSpec")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andLike("status","%"+searchMap.get("status")+"%");
            }

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
